package com.lhl.jwt.security.handler;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lhl.jwt.security.utils.CacheManager;
import com.lhl.jwt.security.utils.JwtConstant;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;

/**
 * @className: com.lhl.jwt.security.handler.LogoutBlacklistHandler
 * @description: 注销登录 将token 加入黑名单
 * @author: king
 * @date: 2020-12-21 23:35
 **/
@Api(tags = "LogoutBlacklistHandler", produces = "LogoutBlacklistHandler")
public class LogoutBlacklistHandler implements LogoutHandler {
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        DecodedJWT jwt = getJwtToken(request);

        CacheManager.setData(jwt.getToken(), jwt, extractExpireTime(jwt));
    }

    private int extractExpireTime(DecodedJWT jwt) {
        int expire = 0;
        Date expiresAt = jwt.getExpiresAt();
        if (!expiresAt.before(Calendar.getInstance().getTime())) {
            expire = (int) (expiresAt.getTime() - System.currentTimeMillis());
        }
        return expire;
    }

    private DecodedJWT getJwtToken(HttpServletRequest request) {
        String authInfo = request.getHeader(JwtConstant.AUTHORIZATION_HEADER);
        if (StringUtils.isBlank(authInfo)) {
            throw new BadCredentialsException(JwtConstant.TOKEN_NOT_EMPTY);
        }
        return JWT.decode(StringUtils.removeStart(authInfo, JwtConstant.AUTHORIZATION_START_STRING));
    }
}
